using System;
using System.Collections.Generic;
using System.Data;
using Orchard.ContentManagement.Drivers;
using Orchard.ContentManagement.MetaData;
using Orchard.ContentManagement.MetaData.Builders;
using Orchard.Core.Contents.Extensions;
using Orchard.Data.Migration;
using RaisingStudio.Trigger.Models;

namespace RaisingStudio.Trigger
{
    public class Migrations : DataMigrationImpl
    {
        public const string TRIGGERS_CONTENTTYPE = "Triggers";
        public const string TRIGGERLOGS_CONTENTTYPE = "TriggerLogs";


        public int Create()
        {
            // Creating table TriggerPartRecord
            SchemaBuilder.CreateTable("TriggerPartRecord", table => table
                .ContentPartRecord()
                .Column("Title", DbType.String)
                .Column("Event", DbType.String)
                .Column("Condition", DbType.String, column => column.Unlimited())
                .Column("Action", DbType.String, column => column.Unlimited())
            );

            // Creating table TriggerLogPartRecord
            SchemaBuilder.CreateTable("TriggerLogPartRecord", table => table
                .ContentPartRecord()
                .Column("TriggerId", DbType.Int32)
                .Column("Title", DbType.String)
                .Column("Event", DbType.String)
                .Column("Condition", DbType.String, column => column.Unlimited())
                .Column("Action", DbType.String, column => column.Unlimited())
                .Column("ContextContentType", DbType.String)
                .Column("ContextContentId", DbType.String)
                .Column("Status", DbType.String)
                .Column("ConditionResult", DbType.String, column => column.Unlimited())
                .Column("ActionResult", DbType.String, column => column.Unlimited())
                .Column("TriggerBeginTime", DbType.String)
                .Column("TriggerEndTime", DbType.String)
            );

            ContentDefinitionManager.AlterPartDefinition(typeof(TriggerPart).Name,
                builder => builder.Attachable());

            ContentDefinitionManager.AlterPartDefinition(typeof(TriggerLogPart).Name,
              builder => builder.Attachable());

            ContentDefinitionManager.AlterTypeDefinition(TRIGGERS_CONTENTTYPE, cfg => cfg
                .WithPart("CommonPart")
                .WithPart(typeof(TriggerPart).Name)
                .Creatable()
                .Draftable());

            ContentDefinitionManager.AlterTypeDefinition(TRIGGERLOGS_CONTENTTYPE, cfg => cfg
                .WithPart("CommonPart")
                .WithPart(typeof(TriggerLogPart).Name)
                .Creatable()
                .Draftable());

            return 1;
        }
    }
}